using BasicScript.Component;
using Game.Core;
using Game.Main.Model;
using Game.Manager;
using SimpleJSON;
using UnityEngine;

namespace Game.Component
{
	public class ClickChangerItem : BaseItem
	{
		public enum State
		{
			Close = 0,
			Open = 1
		}

		public enum Anim
		{
			Static = 0,
			Open = 1,
			Close = 2
		}

		private State state;

		private Transform open;

		private Transform close;

		private FrameAnimation frameAnim;

		private Anim anim;

		public override void Init(ItemArchiveData data)
		{
			base.Init(data);
			state = (State)data.state;
			frameAnim = model.GetComponent<FrameAnimation>();
			open = model.Find("Open");
			close = model.Find("Close");
			SetState(state);
		}

		protected override void LateUpdate()
		{
			base.LateUpdate();
			if (anim != 0 && frameAnim != null && !frameAnim.isPlaying)
			{
				if (anim == Anim.Open)
				{
					anim = Anim.Static;
					SetState(State.Open);
				}
				else if (anim == Anim.Close)
				{
					anim = Anim.Static;
					SetState(State.Close);
				}
			}
		}

		private void SetState(State val)
		{
			state = val;
			if (state == State.Open)
			{
				BoxCollider2D component = open.GetComponent<BoxCollider2D>();
				coll.offset = component.offset + (Vector2)component.transform.localPosition;
				coll.size = component.size;
				if (frameAnim == null)
				{
					open.gameObject.SetActive(true);
					close.gameObject.SetActive(false);
				}
				else
				{
					frameAnim.GotoLastFrame();
				}
			}
			else
			{
				BoxCollider2D component2 = close.GetComponent<BoxCollider2D>();
				coll.offset = component2.offset + (Vector2)component2.transform.localPosition;
				coll.size = component2.size;
				if (frameAnim == null)
				{
					open.gameObject.SetActive(false);
					close.gameObject.SetActive(true);
				}
				else
				{
					frameAnim.GotoFirstFrame();
				}
			}
		}

		public override void QuicklyTouch(TouchEventData touchEventData)
		{
			base.QuicklyTouch(touchEventData);
			if (anim != 0)
			{
				return;
			}
			if (state == State.Close)
			{
				PlayOCSound();
				if (frameAnim != null)
				{
					anim = Anim.Open;
					frameAnim.Play();
				}
				else
				{
					SetState(State.Open);
				}
			}
			else
			{
				PlayOCSound();
				if (frameAnim != null)
				{
					anim = Anim.Close;
					frameAnim.PlayReversed();
				}
				else
				{
					SetState(State.Close);
				}
			}
		}

		private void PlayOCSound()
		{
			if (base.itemData.quicklyClickSound != null && base.itemData.quicklyClickSound.Length == 2)
			{
				if (state == State.Close)
				{
					Singleton<AudioManager>.Instance.PlaySound(base.itemData.quicklyClickSound[0]);
				}
				else
				{
					Singleton<AudioManager>.Instance.PlaySound(base.itemData.quicklyClickSound[1]);
				}
			}
		}

		public override void PlayQuicklyClickSound()
		{
		}

		public override void PackData(JSONObject obj)
		{
			base.PackData(obj);
			if (state != 0)
			{
				obj["33"] = (int)state;
			}
		}
	}
}
